/**
 * 
 * @author mithun
 */

//var console = window.loadFirebugConsole();

$(document.body).startWaiting('bigWaiting');
	
Event.observe(window, 'load', function(event) {
	
	collapseAllMediaPlanBoxesExceptFirst();
	$(document.body).stopWaiting('bigWaiting');
	
});


var removeMediaFromNodePlan = function(el) {
	
	var boxId = el.parentNode.parentNode.id.replace('selectedMedias-', '');
	
	el.parentNode.parentNode.removeChild(el.parentNode);
	
	checkNodePlanDuration(boxId);
	
}

var addMediaToNodePlan = function(el) {
	
	if (el.parentNode.id.match("specialMedias-")) {
		var boxId = el.parentNode.id.replace('specialMedias-', '');
		var mediaDuaration = getTimeInSeconds(el.attributes.value.nodeValue);
		var durationHtmlString = "<em><input type='text' value='" + mediaDuaration + "' onchange='checkSpecialMediaDuration(this);' />secs</em>";
	} else if (el.parentNode.id.match("availableMedias-")) {
		var boxId = el.parentNode.id.replace('availableMedias-', '');
		var durationHtmlString = "";
	} else {
		return;		
	}
		
	
	cloneDiv = el.cloneNode(true);
	cloneDiv.innerHTML = cloneDiv.innerHTML+durationHtmlString+"<span class='crossButton' onclick='removeMediaFromNodePlan(this);'>&nbsp;&nbsp;&nbsp;&nbsp;</span>"; 
	cloneDiv.onclick = function () {
		toggleMediaSelection(this);
	};
	$('selectedMedias-'+boxId).appendChild(cloneDiv);
	$('selectedMedias-'+boxId).scrollTop = $('selectedMedias-'+boxId).scrollHeight;
	
	checkNodePlanDuration(boxId);
		
}

var toggleMediaSelection = function (el) {
	
	if (hasClassName(el, 'move-select')) {
		removeClassName(el, 'move-select');
	} else {
		addClassName(el, 'move-select');
	}
	
}

var moveSelectedMediasDown = function(boxId) {
	
	var selectedMediaDivs = $('selectedMedias-'+boxId).getElementsBySelector('div');
	var mediaCloneArray   = new Array();
	var cloneArrayIndex   = 0;
	var tmp = null;
	var i = 0;
	for (i = 0; i < selectedMediaDivs.length; i++) {
		mediaCloneArray[cloneArrayIndex++] = selectedMediaDivs[i].cloneNode(true);
	}

	for (i = mediaCloneArray.length-2; i >= 0; i--) {
		if (hasClassName(mediaCloneArray[i], 'move-select') && !hasClassName(mediaCloneArray[i+1], 'move-select')) {
			tmp = mediaCloneArray[i];
			mediaCloneArray[i]   = mediaCloneArray[i+1];
			mediaCloneArray[i+1] = tmp;
		}
	}
	
	$('selectedMedias-'+boxId).innerHTML = "";
	for (i = 0; i < mediaCloneArray.length; i++) {
		mediaCloneArray[i].onclick = function () {
			toggleMediaSelection(this);
		};
		$('selectedMedias-'+boxId).appendChild(mediaCloneArray[i]);
	}
	
}

var moveSelectedMediasUp = function(boxId) {
	
	var selectedMediaDivs = $('selectedMedias-'+boxId).getElementsBySelector('div');
	var mediaCloneArray   = new Array();
	var cloneArrayIndex   = 0;
	var tmp = null;
	var i = 0;
	
	for (i = 0; i < selectedMediaDivs.length; i++) {
		mediaCloneArray[cloneArrayIndex++] = selectedMediaDivs[i].cloneNode(true);
	}

	for (i = 1; i < mediaCloneArray.length; i++) {
		if (hasClassName(mediaCloneArray[i], 'move-select') && !hasClassName(mediaCloneArray[i-1], 'move-select')) {
			tmp = mediaCloneArray[i];
			mediaCloneArray[i]   = mediaCloneArray[i-1];
			mediaCloneArray[i-1] = tmp;
		}
	}
	
	$('selectedMedias-'+boxId).innerHTML = "";
	for (i = 0; i < mediaCloneArray.length; i++) {
		mediaCloneArray[i].onclick = function () {
			toggleMediaSelection(this);
		};
		$('selectedMedias-'+boxId).appendChild(mediaCloneArray[i]);
	}
	
}

var NodeMediaPlanDetails = function(mediaPlanId) {
	
	this.getNextNodeMediaPlanId = function(mediaPlanId) {
		var flag = false;
		var selectedMediasGroup  = document.getElementsByClassName('selectedMediasGroup');
		for (var i = 0; i < selectedMediasGroup.length; i++) {
			tempId = selectedMediasGroup[i].id.replace('selectedMedias-', '');
			if (tempId == mediaPlanId) {
				flag = true;
				break;	
			}
		}
		if (flag && i < selectedMediasGroup.length-1) {
			return selectedMediasGroup[i+1].id.replace('selectedMedias-', '');
		} else {
			return null;
		}
	} 
	this.getMediaPlanTimeScheduleArrivalDay = function(mediaPlanId){
		return (mediaPlanId) ? $F('MediaPlanTimeScheduleArrivalDay-'+mediaPlanId) : null;
	}
	this.getMediaPlanTimeScheduleArrivalTime = function(mediaPlanId){
		return (mediaPlanId) ? $F('MediaPlanTimeScheduleArrivalTime-'+mediaPlanId) : null;
	}
	this.getMediaPlanTimeScheduleDepartureDay = function(mediaPlanId){
		return (mediaPlanId) ? $F('MediaPlanTimeScheduleDepartureDay-'+mediaPlanId) : null;
	}
	this.getMediaPlanTimeScheduleDepartureTime = function(mediaPlanId){
		return (mediaPlanId) ? $F('MediaPlanTimeScheduleDepartureTime-'+mediaPlanId) : null;
	}
	this.getAvailableDuration = function() {
		if (this.nextNodeMediaPlanId) {
			return getTimeDifference(this.mediaPlanTimeScheduleArrivalDay, this.mediaPlanTimeScheduleArrivalTime, this.nextNodeMediaPlanArrivalDay, this.nextNodeMediaPlanArrivalTime);
		}
	}
	this.getCurrentPlanDuration = function() {
		var selectedMedias  = $('selectedMedias-'+this.mediaPlanId);
		var selectedMediaItems  = selectedMedias.getElementsBySelector('DIV');
		var totalDuration = 0;
		for (var i = 0; i < selectedMediaItems.length; i++) {
			if (selectedMediaItems[i].hasClassName('specialMedia')) {
				continue; // Donot consider special media duarion for total node plan duration.
			}
			//selectedMediaItemss[i].value = (selectedMediaItems[i].value) ?  selectedMediaItems[i]. value : selectedMediaItems[i].attributes.value.nodeValue;
			var mediaDuration = selectedMediaItems[i].attributes.value.nodeValue;
			totalDuration = totalDuration + getTimeInSeconds(mediaDuration);
		}
		return totalDuration;
	}
	
	this.mediaPlanId                        = mediaPlanId;
	this.mediaPlanTimeScheduleArrivalDay    = this.getMediaPlanTimeScheduleArrivalDay(this.mediaPlanId);
	this.mediaPlanTimeScheduleArrivalTime   = this.getMediaPlanTimeScheduleArrivalTime(this.mediaPlanId);
	this.mediaPlanTimeScheduleDepartureDay  = this.getMediaPlanTimeScheduleDepartureDay(this.mediaPlanId);
	this.mediaPlanTimeScheduleDepartureTime = this.getMediaPlanTimeScheduleDepartureTime(this.mediaPlanId);;
	this.nextNodeMediaPlanId                = this.getNextNodeMediaPlanId(this.mediaPlanId);
	this.nextNodeMediaPlanArrivalDay        = this.getMediaPlanTimeScheduleArrivalDay(this.nextNodeMediaPlanId);
	this.nextNodeMediaPlanArrivalTime       = this.getMediaPlanTimeScheduleArrivalTime(this.nextNodeMediaPlanId);
	this.availableDuration                  = this.getAvailableDuration();
	this.currentPlanDuration                = this.getCurrentPlanDuration();
	this.excessTime                         = this.currentPlanDuration - this.availableDuration;
	this.planOk                             = (this.availableDuration) ? (this.availableDuration >= this.currentPlanDuration) : true;
	this.nodeName                           = $F('MediaPlanNodeName-'+this.mediaPlanId);
	
}

var checkNodePlanDuration = function(boxId) {
	
	var nodeMediaPlanDetails = new NodeMediaPlanDetails(boxId);
	if (!nodeMediaPlanDetails.planOk) {
		showMediaDurationExceedWarning(nodeMediaPlanDetails);
		//alert("Total Media duration for for this node exceed the available time.\n\tPlease remove some media from this node plan.");
	} else {
  		hideMediaDurationExceedWarning(nodeMediaPlanDetails);
	} 
	
}

var checkSpecialMediaDuration = function(el) {
	
	var isInteger = /^-?\d+$/.test(el.value);
	if (isInteger) {
		// Donot validate spacial medias
		el.parentNode.parentNode.value = convertSecondsToHhMmSsFormat(el.value);
		el.parentNode.parentNode.attributes.value.nodeValue = convertSecondsToHhMmSsFormat(el.value)
	//	console.debug(el.parentNode.parentNode.value);
		 return; 
		if (el.parentNode.parentNode.parentNode.id.match("selectedMedias-")) {
			var mediaPlanId = el.parentNode.parentNode.parentNode.id.replace('selectedMedias-', '');
			var nodeMediaPlanDetails = new NodeMediaPlanDetails(mediaPlanId);
			if (!nodeMediaPlanDetails.planOk) {
				showMediaDurationExceedWarning(nodeMediaPlanDetails);
				//alert("Total Media duration for for this node exceed the available time.\n\tPlease remove some media from this node plan.");
			} else {
				hideMediaDurationExceedWarning(nodeMediaPlanDetails);
			}
		}
	} else {
		alert("Please specify seconds in digits only")
		el.value = 0;
	}
	
}

var showMediaDurationExceedWarning = function(nodeMediaPlanDetails) {
	
	var message = "Total Media duration exceeded by "+ nodeMediaPlanDetails.excessTime + " seconds.<br />Available slot duraion is only "+nodeMediaPlanDetails.availableDuration+ " seconds.";
	$('mediaPlanDurationWarn-'+nodeMediaPlanDetails.mediaPlanId).innerHTML = message;
	
}

var hideMediaDurationExceedWarning = function(nodeMediaPlanDetails) {
	
	var message = "";
	$('mediaPlanDurationWarn-'+nodeMediaPlanDetails.mediaPlanId).innerHTML = message;
	
}

var convertSecondsToHhMmSsFormat = function(duration) {
	
	duration  = parseInt(duration);
	var hours = 0; 	
	var mins  = 0; 	
	var secs  = 0; 	
	if (duration >= (60 * 60)) {
		var hours = duration/(60 * 60 );
		hours     =  parseInt(hours);
		//hours = Math.round(hours);
	}
	duration = duration - (hours * 60 * 60 ); 	
	duration =  parseInt(duration);
	if (duration >= 60) {
		var mins = duration/60;
		mins =  parseInt(mins);
		//mins = Math.round(mins);
	} 	
	duration = duration - (mins * 60 ); 	
	duration = parseInt(duration);
	secs     = duration;
	
	hours    = (hours >= 10) ? hours : '0' + hours;
	mins     = (mins >= 10)  ? mins  : '0' + mins;
	secs     = (secs >= 10)  ? secs  : '0' + secs;
	
	return hours + ":" + mins + ":" + secs;
	
}

var collapseAllMediaPlanBoxes = function() {
	
	var mediaPlans = document.getElementsByClassName('mediaPlanBox');
	for (var i = 0; i < mediaPlans.length; i++) {
		var mediaPlanId = mediaPlans[i].id.replace('mediaPlanBox-', '');
		new Effect.BlindUp($('mediaPlanBoxBody-'+mediaPlanId), {duration:0.5});
		changeArrowImage(mediaPlanId, 'down');
	}
}

var collapseAllMediaPlanBoxesExceptFirst = function() {
	
	var mediaPlans = document.getElementsByClassName('mediaPlanBox');
	for (var i = 1; i < mediaPlans.length; i++) {
		var mediaPlanId = mediaPlans[i].id.replace('mediaPlanBox-', '');
		new Effect.BlindUp($('mediaPlanBoxBody-'+mediaPlanId), {duration:0.5});
		changeArrowImage(mediaPlanId, 'down');
	}
}

var expandAllMediaPlanBoxes = function() {
	
	var mediaPlans = document.getElementsByClassName('mediaPlanBox');
	for (var i = 0; i < mediaPlans.length; i++) {
		var mediaPlanId = mediaPlans[i].id.replace('mediaPlanBox-', '');
		if (!isShowingContents(mediaPlanId)) {
			new Effect.BlindDown($('mediaPlanBoxBody-' + mediaPlanId), {
				duration: 0.5
			});
			changeArrowImage(mediaPlanId, 'up');
		}
	}
}


var toggleMediaPlanBox = function(mediaPlanId) {

	if (isShowingContents(mediaPlanId)) {
		$('mediaPlanBoxBody-'+mediaPlanId).setStyle({ overflow: 'hidden' });
		new Effect.BlindUp($('mediaPlanBoxBody-'+mediaPlanId), {duration:0.5});
		changeArrowImage(mediaPlanId, 'down');
	} else {
		$('mediaPlanBoxBody-'+mediaPlanId).setStyle({ overflow: 'scroll' });
		new Effect.BlindDown($('mediaPlanBoxBody-'+mediaPlanId), {duration:0.5});		
		changeArrowImage(mediaPlanId, 'up');
	}
	
}

var isShowingContents = function(mediaPlanId) {
	
	var arrowImg = $('mediaPlanBox-'+mediaPlanId).getElementsBySelector('img')[0];
	if (arrowImg.src.match("arrow2_n.gif")) {
		return true;
	} else {
		return false;
	}
	
} 

var changeArrowImage = function(mediaPlanId, direction) {
	
	var arrowImg = $('mediaPlanBox-'+mediaPlanId).getElementsBySelector('img')[0];
	if (direction == 'up') {
		arrowImg.alt = '&uArr;'
		arrowImg.src = arrowImg.src.replace("arrow2_s.gif", "arrow2_n.gif")		
	} else if (direction == 'down') {
		arrowImg.alt = '&dArr;'				
		arrowImg.src = arrowImg.src.replace("arrow2_n.gif", "arrow2_s.gif")		
	}
	
}

var checkForm = function() {

	var flag = true;
	var mediaPlanId;
	var mediaPlanTriggerCondition = 'A';
	var mediaPlanInitialDelayCondition = 'SI';
	var mediaPlanInitialDelayValue;
	var mediaPlanIntermediateDelay;
	var mediaPlanLoopTillNextTrigger;
	var mediaPlanLoopIterationDelay;
	var mediaPlans = document.getElementsByClassName('mediaPlanBox');
	
	for (var i = 0; i < mediaPlans.length; i++) {
		mediaPlanId                    = mediaPlans[i].id.replace('mediaPlanBox-', '');
		var nodeMediaPlanDetails = new NodeMediaPlanDetails(mediaPlanId);
		if (!nodeMediaPlanDetails.planOk) {
	//	console.debug(nodeMediaPlanDetails);
			//alert("Total Media duration for node " +nodeMediaPlanDetails.nodeName + " exceed the available time.\n\tPlease remove some media from this node plan.");
			//return false;
			if (confirm("Total Media duration for some of nodes exceeded the available duration.\n\t Are you sure you want to continue?")) {
				break;
			} else {
				return false;
			}
		}
	}
	for (var i = 0; i < mediaPlans.length; i++) {
		
		mediaPlanId                    = mediaPlans[i].id.replace('mediaPlanBox-', '');
		mediaPlanTriggerCondition      = ($('MediaPlanMediaPlanTriggerCondition-A-'+mediaPlanId).checked)  ? $F('MediaPlanMediaPlanTriggerCondition-A-'+mediaPlanId)     : mediaPlanTriggerCondition;
		mediaPlanTriggerCondition      = ($('MediaPlanMediaPlanTriggerCondition-D-'+mediaPlanId).checked)  ? $F('MediaPlanMediaPlanTriggerCondition-D-'+mediaPlanId)     : mediaPlanTriggerCondition;
		mediaPlanTriggerCondition      = ($('MediaPlanMediaPlanTriggerCondition-S-'+mediaPlanId).checked)  ? $F('MediaPlanMediaPlanTriggerCondition-S-'+mediaPlanId)     : mediaPlanTriggerCondition;
		mediaPlanInitialDelayCondition = ($('MediaPlanMediaPlanInitialDelay-SI-'+mediaPlanId).checked)     ? $F('MediaPlanMediaPlanInitialDelay-SI-'+mediaPlanId)        : mediaPlanInitialDelayCondition;
		mediaPlanInitialDelayCondition = ($('MediaPlanMediaPlanInitialDelay-SA-'+mediaPlanId).checked)     ? $F('MediaPlanMediaPlanInitialDelay-SA-'+mediaPlanId)        : mediaPlanInitialDelayCondition;
		mediaPlanInitialDelayValue     = ($('MediaPlanMediaPlanInitialDelay-SA-'+mediaPlanId).checked)     ? $F('MediaPlanMediaPlanInitialDelayValue-'+mediaPlanId)      : 0;
		mediaPlanIntermediateDelay     = ($('MediaPlanMediaPlanIntermediateDelay-'+mediaPlanId).checked)   ? $F('MediaPlanMediaPlanIntermediateDelayValue-'+mediaPlanId) : 0;
		mediaPlanLoopTillNextTrigger   = ($('MediaPlanMediaPlanLoopTillNextTrigger-'+mediaPlanId).checked) ? 1 : 0;
		mediaPlanLoopIterationDelay    = ($('MediaPlanMediaPlanLoopTillNextTrigger-'+mediaPlanId).checked) ? $('MediaPlanMediaPlanLoopIterationDelay-'+mediaPlanId)      : 0;
		
		// create form fields for mediaplan	
		addFieldToForm("data[MediaPlans]["+i+"][id]",                                 mediaPlanId);
		addFieldToForm("data[MediaPlans]["+i+"][media_plan_trigger_condition]",       mediaPlanTriggerCondition);
		addFieldToForm("data[MediaPlans]["+i+"][media_plan_initial_delay_condition]", mediaPlanInitialDelayCondition);
		addFieldToForm("data[MediaPlans]["+i+"][media_plan_initial_delay_value]",     mediaPlanInitialDelayValue);
		addFieldToForm("data[MediaPlans]["+i+"][media_plan_intermediate_delay]",      mediaPlanIntermediateDelay);
		addFieldToForm("data[MediaPlans]["+i+"][media_plan_loop_till_next_trigger]",  mediaPlanLoopTillNextTrigger);
		addFieldToForm("data[MediaPlans]["+i+"][media_plan_loop_iteration_delay]",    mediaPlanLoopIterationDelay);
		
		// Add slots for this media plan
		
		var selectedMediasHolder = $('selectedMedias-'+mediaPlanId);
		var selectedMedias = selectedMediasHolder.getElementsBySelector('div');
		for (var j = 0; j < selectedMedias.length; j++) {
			var mediaId = selectedMedias[j].id.replace('item_'+mediaPlanId+"_", ''); 
			addFieldToForm("data[MediaPlans]["+i+"][MediaPlanSlots]["+j+"][id]", "");
			addFieldToForm("data[MediaPlans]["+i+"][MediaPlanSlots]["+j+"][media_id]", mediaId);
			addFieldToForm("data[MediaPlans]["+i+"][MediaPlanSlots]["+j+"][media_plan_slot_sequence_no]", j+1);
			selectedMedias[j].value = (selectedMedias[j].value) ?  selectedMedias[j].value : selectedMedias[j].attributes.value.nodeValue;
			addFieldToForm("data[MediaPlans]["+i+"][MediaPlanSlots]["+j+"][media_plan_slot_duration]", selectedMedias[j].value);
		}  
		
	}
	if (flag) {
		addFieldToForm("data[JavaScriptCheck]", 1);
	}
	return flag;

} 


var addFieldToForm = function(fieldName, fieldValue) {
	
	var formField = document.createElement('INPUT');
	formField.setAttribute('type', 'hidden');
	formField.setAttribute('name', fieldName);
	formField.value = fieldValue;
	document.getElementsByTagName('form')[0].appendChild(formField);
	 
}

var getTimeInSeconds = function(time) {
	
	var timeInSeconds = parseInt(time.charAt(0) + time.charAt(1), 10) * 60 * 60 + parseInt(time.charAt(3) + time.charAt(4), 10) * 60 + parseInt(time.charAt(6) + time.charAt(7), 10);
	return timeInSeconds;
}


var getTimeDifference = function(day1, time1, day2, time2) {
	
	
	var time1InSeconds = getTimeInSeconds(time1);
	var time2InSeconds = getTimeInSeconds(time2);
	//console.debug(time2InSeconds, time1InSeconds);
	
	if (day1 == -1 && day2 == -1) {
		return (time2InSeconds - time1InSeconds);
	} else if (day1 == day2) {
		return (time2InSeconds - time1InSeconds);
	} else if (day2 > day1) {
		var dayDifferenceInSeconds = (day2 - day1 - 1) * (24 * 60 * 60);
		var remainingSecondsInDay1 = (24 * 60 * 60) - time1InSeconds;
		var totalTimeDifferenceInSeconds = dayDifferenceInSeconds + remainingSecondsInDay1 + time2InSeconds;
		return totalTimeDifferenceInSeconds;
	} else if (day2 < day1) {
		var totalSecondsInAWeek = 7 * 24 * 60 * 60; 
		var remainingSecondsInWeek =  totalSecondsInAWeek - (day1 * (24 * 60 * 60) + time1InSeconds);
		var secondsInNextNeek = day2 * (24 * 60 * 60) + time2InSeconds; 
		var totalTimeDifferenceInSeconds = remainingSecondsInWeek + secondsInNextNeek;
		return totalTimeDifferenceInSeconds;
	}
	
}


var hasClassName = function(el, className) {
	
	if (Prototype.Browser.IE) {
		if (el.className.match(className)) {
			return true;	
		} else {
			return false;
		}
	} else {
		return el.hasClassName(className);
	}
	
}

var addClassName = function(el, className) {
	
	if (Prototype.Browser.IE) {
		if (el.className.match(className) == null) {
			el.className = el.className + ' ' + className;	
		}
	} else {
		el.addClassName(className);
	}
	
}

var removeClassName = function(el, className) {
	
	if (Prototype.Browser.IE) {
		el.className = el.className.replace(className,"");
	} else {
		el.removeClassName(className);
	}
	
}
